<template>
  <div class="knowledge">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-right">
            <h2>农业知识大讲堂</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="content-container">
          <!-- 左侧分类栏 -->
          <div class="category-sidebar">
            <h3 class="sidebar-title">知识分类</h3>
            <el-menu
              :default-active="activeCategory"
              class="category-menu"
              @select="handleCategorySelect"
            >
              <el-menu-item 
                v-for="category in categories" 
                :key="category.id" 
                :index="category.id.toString()"
              >
                <el-icon><Folder /></el-icon>
                <span>{{ category.name }}</span>
              </el-menu-item>
            </el-menu>
          </div>

          <!-- 右侧文章列表 -->
          <div class="article-container">
            <!-- 搜索和发布按钮 -->
            <div class="action-bar">
              <el-input
                v-model="searchQuery"
                placeholder="搜索文章..."
                class="search-input"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button type="primary" @click="showCreateDialog" v-if="userStore.isLoggedIn">
                <el-icon><Plus /></el-icon>
                发布文章
              </el-button>
            </div>

            <!-- 文章列表 -->
            <div class="article-list">
              <el-card 
                v-for="article in articles" 
                :key="article.plantId" 
                class="article-card"
                @click="viewArticle(article)"
              >
                <div class="article-header">
                  <div class="title-status">
                    <h3 class="article-title">{{ article.name }}</h3>
                    <el-tag 
                      v-if="activeCategory === '6'"
                      :type="article.status === 1 ? 'success' : 'info'"
                      size="small"
                    >
                      {{ article.status === 1 ? '已发布' : '草稿' }}
                    </el-tag>
                  </div>
                </div>
                <div class="article-content">
                  <div class="article-image" v-if="article.imageUrl">
                    <img :src="article.imageUrl" :alt="article.name">
                  </div>
                  <p class="article-description">{{ article.description }}</p>
                </div>
                <div class="article-footer">
                  <div class="article-info">
                    <span class="publish-time">{{ formatDate(article.createdAt) }}</span>
                  </div>
                </div>
              </el-card>
            </div>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="total"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 发布文章对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="发布文章"
      width="70%"
    >
      <template #header>
        <div class="dialog-header">
          <span>发布文章</span>
        </div>
      </template>
      <el-form :model="articleForm" :rules="articleRules" ref="articleFormRef">
        <el-form-item label="标题" prop="name">
          <el-input v-model="articleForm.name" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="封面图片" prop="image">
          <el-upload
            class="article-image-upload"
            :show-file-list="false"
            :on-change="handleImageUpload"
            :before-upload="beforeImageUpload"
            accept="image/*"
          >
            <div v-if="!articleForm.imageUrl" class="upload-placeholder">
              <el-icon><Plus /></el-icon>
              <span>点击上传封面图片</span>
            </div>
            <img v-else :src="articleForm.imageUrl" class="preview-image">
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="description">
          <el-input
            v-model="articleForm.description"
            type="textarea"
            :rows="10"
            placeholder="请输入文章内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreateArticle">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Folder, Search, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getArticleList, createArticle, getUserArticleList } from '@/api/plants'

const router = useRouter()
const userStore = useUserStore()

// 状态变量
const loading = ref(false)
const activeCategory = ref('0')
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const createDialogVisible = ref(false)
const articleFormRef = ref(null)

// 数据列表
const categories = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '种植技术' },
  { id: 2, name: '病虫害防治' },
  { id: 3, name: '农业政策' },
  { id: 4, name: '市场行情' },
  { id: 5, name: '农业科技' },
  { id: 6, name: '我发布的' }
])

const articles = ref([])

// 表单数据
const articleForm = reactive({
  name: '',
  description: '',
  image: null,
  imageUrl: ''
})

// 表单验证规则
const articleRules = {
  name: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 方法
const loadArticles = async () => {
  loading.value = true
  console.log('开始加载文章列表...')
  try {
    if (!userStore.isLoggedIn) {
      console.log('用户未登录')
      ElMessage.warning('请先登录后查看文章')
      articles.value = []
      total.value = 0
      loading.value = false
      return
    }

    console.log('发送获取文章列表请求...')
    let response
    if (activeCategory.value === '6') {  // "我发布的"分类
      response = await getUserArticleList()
    } else {
      response = await getArticleList()
    }
    console.log('获取文章列表响应:', response)
    
    if (Array.isArray(response)) {
      console.log('文章数据:', response)
      articles.value = response
      total.value = articles.value.length
      console.log('文章列表加载成功，总数:', total.value)
    } else if (response && response.data) {
      console.log('文章数据:', response.data)
      articles.value = Array.isArray(response.data) ? response.data : []
      total.value = articles.value.length
      console.log('文章列表加载成功，总数:', total.value)
    } else {
      console.error('加载失败，响应数据无效:', response)
      ElMessage.error('获取文章列表失败')
    }
  } catch (error) {
    console.error('加载文章列表出错，详细错误:', error)
    if (error?.response?.status === 401) {
      ElMessage.warning('请先登录后查看文章')
      articles.value = []
      total.value = 0
    } else {
      ElMessage.error(error?.response?.data?.message || '获取文章列表失败')
    }
  } finally {
    loading.value = false
  }
}

const handleCategorySelect = (categoryId) => {
  activeCategory.value = categoryId
  currentPage.value = 1
  loadArticles()
}

const handleSearch = () => {
  currentPage.value = 1
  loadArticles()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadArticles()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadArticles()
}

const showCreateDialog = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }
  createDialogVisible.value = true
}

const handleImageUpload = (uploadFile) => {
  if (uploadFile && uploadFile.raw) {
    articleForm.image = uploadFile.raw
    articleForm.imageUrl = URL.createObjectURL(uploadFile.raw)
  }
  return false // 阻止自动上传
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleCreateArticle = async () => {
  if (!articleFormRef.value) return
  
  await articleFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log('开始发布文章，表单数据:', articleForm)
      try {
        const formData = new FormData()
        formData.append('name', articleForm.name)
        formData.append('description', articleForm.description)
        if (articleForm.image) {
          formData.append('image', articleForm.image)
        }

        const response = await createArticle(formData)
        console.log('发布文章响应:', response)
        
        if (response?.code === 1 || (response && response.name && response.description)) {
          console.log('文章发布成功')
          ElMessage.success('发布成功')
          createDialogVisible.value = false
          loadArticles()
          // 重置表单
          articleForm.name = ''
          articleForm.description = ''
          articleForm.image = null
          if (articleForm.imageUrl) {
            URL.revokeObjectURL(articleForm.imageUrl)
            articleForm.imageUrl = ''
          }
        } else {
          console.error('发布失败，响应:', response)
          ElMessage.error('发布失败')
        }
      } catch (error) {
        console.error('发布文章时出错，详细错误:', error)
        ElMessage.error(error?.response?.data?.message || '发布文章失败')
      }
    } else {
      console.log('表单验证失败')
    }
  })
}

const viewArticle = (article) => {
  router.push(`/knowledge/article/${article.plantId}`)
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadArticles()
})

// 在组件卸载时清理 URL
onBeforeUnmount(() => {
  if (articleForm.imageUrl) {
    URL.revokeObjectURL(articleForm.imageUrl)
  }
})
</script>

<style scoped>
.knowledge {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.content-container {
  display: flex;
  gap: 20px;
  margin: 20px;
}

.category-sidebar {
  width: 240px;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.sidebar-title {
  padding: 0 20px;
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}

.category-menu {
  border-right: none;
}

.article-container {
  flex: 1;
  min-width: 0;
}

.action-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.article-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.article-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.article-header {
  margin-bottom: 12px;
}

.title-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.article-title {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.article-content {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.article-image {
  width: 200px;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
}

.article-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.article-description {
  flex: 1;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.article-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.publish-time {
  font-size: 14px;
  color: #999;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.article-image-upload {
  width: 100%;
}

.article-image-upload :deep(.el-upload) {
  width: 100%;
}

.upload-placeholder {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-placeholder:hover {
  border-color: var(--el-color-primary);
}

.upload-placeholder .el-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.preview-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}
</style> 